Vue.component("common",{
    template:`
    <nav class="top-nav">
        <div class="nav-logo">
            <img src="../image/Bilibili.png" style="margin:30px;width: 34px; height: 34px;" @click="location.href = '../index.html'">
        </div>

        <ul class="nav-links">
            
            <li class="nav-item">
                <a href="../index.html" class="nav-link" >主站</a>
            </li>
            <li class="nav-item">
<!--                <a href="#" class="nav-link">番剧</a>-->
            </li>
            <li class="nav-item">
                <a href="#" class="nav-link">会员购</a>
            </li>
            <li class="nav-item">
<!--                <a href="#" class="nav-link">动态</a>-->
            </li>
            
        </ul>

        <div class="nav-right" v-if="myinfo">
            <li><img :src="myinfo.headimg" width="" class="headimg" @click="location.href = '../me.html?id=' + myinfo.id"></li>
            <li @click="location.href = '../me.html?id=' + myinfo.id">欢迎: {{myinfo.name}}</li>
            <li class="nav-item">
                <a href="#" class="nav-link" @click="logout">退出</a>
            </li>
        </div>
        
        <div class="nav-right" v-else>
            <li><a href="#" @click.prevent="isShowLoginWin">注册</a></li>
            <li><a href="#" @click.prevent="isShowLoginWin">登录</a></li>
        </div>
         
    </div>
</div> 

     <div id="body" v-show="showLoginWin">
        <!-- 登录弹窗 -->
        <div class="modal-overlay hidden" id="loginModal">
            <div class="login-modal">
    
    
                <!-- 左侧二维码部分 -->
                <div class="qr-section">
                    <div class="login-close" id="closeLoginModal" @click="showLoginWin=false">×</div>
                    <div id="qrcode" @click="refreshCode" ref="ImageCode">
                      <img ref="qrImage" id="qr-image" :src="imageCode" alt="QR Code" crossorigin="anonymous">
                    </div>
                    <canvas ref="qrCanvas" id="qr-canvas" style="display:none;"></canvas>
                    <p id="tip">请使用APP扫描二维码登录</p>
                    <p ref="tipFresh">点击二维码可刷新</p>            
                    <div class="qr-text">
                        请使用 哔哩哔哩客户端扫码登录<br>或扫码下载APP
                    </div>
                </div>
    
                <!-- 右侧登录表单部分 -->
                <div class="login-section">
                    <!-- 登录方式切换 -->
                    <div class="login-header">
                        <div ref="passwordLogin" class="login-tab active" data-tab="password" @click="passwordLogin">密码登录</div>
                        <div ref="emailLogin" class="login-tab" data-tab="sms" @click="emailLogin">邮箱登录</div>
                    </div>
    
                    <!-- 密码登录表单 -->
                    <div class="login-form" id="passwordLogin" v-show="isLoginByPassword">
                        <div class="form-group">
                            <label class="form-label">账号</label>
                            <input type="text" class="form-input" placeholder="请输入账号" v-model="form.username">
                        </div>
                        <div class="form-group">
                            <label class="form-label">密码</label>
                            <div class="password-group">
                                <input type="password" class="form-input" placeholder="请输入密码" id="passwordInput" v-model="form.password">
                                <span class="toggle-password" id="togglePassword">显示</span>
                            </div>
                        </div>
                        <div class="forgot-password">
                            <a href="#">忘记密码？</a>
                        </div>
                        <button class="login-btn" @click="login">登录</button>
                        <div class="register-link">
                            <a href="#" id="switchToRegister" @click="Reg">注册</a>
                        </div>
                    </div>
    
                    <!-- 短信登录表单 -->
                    <div class="login-form hidden" id="smsLogin" v-show="isLoginByEmail" style="display: flex;flex-direction: column;gap: 20px">
                        <div class="phone-group">
                            <input type="text" class="form-input" placeholder="请输入邮箱" v-model="email">
                        </div>
                        <div class="code-group">
                            <input type="text" class="form-input" placeholder="请输入验证码">
                            <button class="get-code-btn" @click="SendCode" v-model="code" ref="getCodeBtn">获取验证码</button>
                        </div>
                        <button class="login-btn" @click="loginByEmail">登录/注册</button>  
                    </div>
    
                    <!-- 注册表单 -->
    <!--                <div class="login-form hidden" id="registerForm" v-show="isReg">-->
    <!--                    <div class="form-group">-->
    <!--                        <label class="form-label">邮箱</label>-->
    <!--                        <input type="email" class="form-input" placeholder="请输入邮箱">-->
    <!--                    </div>-->
    <!--                    <div class="code-group">-->
    <!--                        <input type="text" class="form-input" placeholder="请输入验证码">-->
    <!--                        <button class="get-code-btn">获取验证码</button>-->
    <!--                    </div>-->
    <!--                    <button class="login-btn">注册</button>-->
    <!--                    <div class="register-link">-->
    <!--                        <a href="#" id="switchToLogin">已有账号？立即登录</a>-->
    <!--                    </div>-->
    <!--                    &lt;!&ndash; <div class="other-login">-->
    <!--                        其他方式登录-->
    <!--                    </div>-->
    <!--                    <div class="social-login">-->
    <!--                        <div class="social-icon">微</div>-->
    <!--                        <div class="social-icon">微</div>-->
    <!--                        <div class="social-icon">Q</div>-->
    <!--                    </div>-->
    <!--                    <div class="agreement">-->
    <!--                        未注册过哔哩哔哩的手机号，我们将自动帮你注册账号<br>-->
    <!--                        登录或完成注册即代表你同意 <a href="#">用户协议</a> 和 <a href="#">隐私政策</a>-->
    <!--                    </div> &ndash;&gt;-->
    <!--                </div>-->
                </div>
            </div>
        </div>
    </div>
        </div>
       
    </nav>
    
    `,

    data(){
        return {
            myinfo:null,
            form:{
                username:"",
                password:"",
            },
            usernameColumn:null,
            showLoginWin: false,
            isLoginByPassword: true,
            isLoginByEmail: false,
            email: null,
            code : null,
            imageCode: null,
        }
    },
    created(){

        // 添加请求拦截器
        axios.interceptors.request.use(function (config) {
            // 在发送请求之前做些什么
            var jwt = localStorage.getItem("jwt");
            if (jwt) {
                config.headers.authorization = jwt;
            }
            return config;
        }, function (error) {
            // 对请求错误做些什么
            return Promise.reject(error);
        });


        // 添加响应拦截器
        axios.interceptors.response.use(function (response) {
            // 2xx 范围内的状态码都会触发该函数。
            // 对响应数据做点什么
            if (response.headers.authorization) {
                localStorage.setItem("jwt", response.headers.authorization);
            }
            return response;
        }, function (error) {
            // 超出 2xx 范围的状态码都会触发该函数。
            // 对响应错误做点什么
            return Promise.reject(error);
        });

        axios.get("b-user/login/myinfo").then(res=> {
            if (res.data.code == 1) {
                this.myinfo = res.data.data;
                console.log("myinfo",this.myinfo)
                this.$emit("logined",this.myinfo);
            }
        });
    },
    methods:{
        login() {
            axios.get("b-user/user/logins", {
                params: this.form
            }).then(res => {
                if (res.data.code == 1) {
                    this.showLoginWin = false;
                    this.$message(res.data.msg);
                    // console.log(res.data.data.user.headimg)
                    this.myinfo = res.data.data;
                    this.$emit("logined", res.data.data);
                    if (res.data.data.goto) {
                        location.href = res.data.data.goto
                    }
                } else {
                    this.$alert(res.data.msg);
                }
            });
        },
        logout(){
            localStorage.removeItem('jwt');
            location.reload(false);
            // location.href = '../index.html'
        },
        isShowLoginWin(){
            this.showLoginWin = true;
            this.productCode();
        },
        emailLogin() {
            this.isLoginByEmail = true
            this.isLoginByPassword = false
            this.$refs.emailLogin.classList.add('active')
            this.$refs.passwordLogin.classList.remove('active')
        },
        Reg() {
            this.isLoginByEmail = true;
            this.isLoginByPassword = false;
            this.$refs.emailLogin.classList.add('active')
            this.$refs.passwordLogin.classList.remove('active')
        },
        loginByEmail() {
            axios.get("b-user/user/loginByEmail", {
                params: {
                    code: this.code,
                    email: this.email
                }
            }).then(res => {
                if (res.data.code == 1) {
                    this.myinfo = res.data.data
                    console.log("res.data.data" + res.data.data)
                    this.showLoginWin = false
                    // 使用 $nextTick 方法，确保在本次 DOM 更新循环结束之后执行回调函数。
                    // 当 Vue 完成数据更新并重新渲染 DOM 之后，再触发 "logined" 事件，
                    // 保证父组件在接收到事件时，DOM 已经更新，数据状态是最新的。
                    this.$nextTick(() => {
                        this.$emit("logined", this.myinfo);
                    });
                }
            })
        },
        SendCode() {
            if (this.email == null) {
                return
            }
            const button = this.$refs.getCodeBtn;
            let countdown = 60;

            // 禁用按钮并设置样式
            button.disabled = true;
            button.classList.add('disabled');
            button.textContent = `请等待 ${countdown} 秒`;

            const interval = setInterval(() => {
                countdown--;
                button.textContent = `请等待 ${countdown} 秒`;

                if (countdown <= 0) {
                    clearInterval(interval);
                    button.disabled = false;
                    button.classList.remove('disabled');
                    button.textContent = '获取验证码';
                }
            }, 1000);
            axios.get("b-user/vcode/email", {
                params: {
                    msgName: "loginMsg",
                    email: this.email,
                }
            }).then(res => {
                if (res.data.code == 1) {
                    this.$message(res.data.msg)
                }
            })
        },
        passwordLogin() {
            this.isLoginByPassword = true
            this.isLoginByEmail = false
            this.$refs.passwordLogin.classList.add('active')
            this.$refs.emailLogin.classList.remove('active')
        },
        emailLogin() {
            this.isLoginByEmail = true
            this.isLoginByPassword = false
            this.$refs.emailLogin.classList.add('active')
            this.$refs.passwordLogin.classList.remove('active')
        },
        async refreshCode() {
            try {
                // 1. 发起GET请求获取二维码图片数据
                const response = await axios.get('http://127.0.0.1:8001/pc/qrCode', {
                    responseType: 'arraybuffer' // 重要！指定接收二进制数据
                });

                // 2. 将二进制数据转换为Base64
                const imageBase64 = btoa(
                    new Uint8Array(response.data).reduce(
                        (data, byte) => data + String.fromCharCode(byte),
                        ''
                    )
                );

                // 3. 设置图片src
                this.imageCode = `data:image/png;base64,${imageBase64}`;
                // 4. 创建临时img元素加载二维码图片
                const img = new Image();
                img.src = this.imageCode;

                // 等待图片加载完成
                await new Promise((resolve) => {
                    img.onload = resolve;
                });

                this.saveImageCode(img);
            } catch (error) {
                console.error('生成二维码失败:', error);
            }
        },
        async productCode() {
            try {
                // 1. 发起GET请求获取二维码图片数据
                const response = await axios.get('http://127.0.0.1:8001/pc/qrCode', {
                    responseType: 'arraybuffer' // 重要！指定接收二进制数据
                });

                // 2. 将二进制数据转换为Base64
                const imageBase64 = btoa(
                    new Uint8Array(response.data).reduce(
                        (data, byte) => data + String.fromCharCode(byte),
                        ''
                    )
                );

                // 3. 设置图片src
                this.imageCode = `data:image/png;base64,${imageBase64}`;
                // 4. 创建临时img元素加载二维码图片
                const img = new Image();
                img.src = this.imageCode;

                // 等待图片加载完成
                await new Promise((resolve) => {
                    img.onload = resolve;
                });

                this.saveImageCode(img);
            } catch (error) {
                console.error('生成二维码失败:', error);

            }
        },
        // 更新提示信息的样式
        updateTip(message, className) {
            const tipElement = document.getElementById('tip');
            tipElement.textContent = message;
            tipElement.className = className;
        },
        saveImageCode(imgs) {
            const img = imgs;
            const canvas = this.$refs.qrCanvas;
            const context = canvas.getContext("2d");
            // 设置 canvas 的大小与图片一致
            canvas.width = img.width;
            canvas.height = img.height;
            // 将图片绘制到 canvas 上
            context.drawImage(img, 0, 0, img.width, img.height);
            // 获取图片的 ImageData
            const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
            // 使用 jsQR 解析二维码
            const code = jsQR(imageData.data, imageData.width, imageData.height);
            // 检查是否识别到二维码
            if (code) {
                socket = new WebSocket("ws://127.0.0.1:8001/websocket/" + code.data);
                socket.onopen = function (event) {
                    console.log("Connected to WebSocket");
                };
                socket.onmessage =  (event)=> {
                    const jData = JSON.parse(event.data);
                    console.log("jData.token" + jData.token)
                    if (jData.token) {
                        this.updateTip("登录成功，pc token为 " + jData.token, 'success-message');
                        axios.get("b-user/pc/loginByImageCode",{
                            params:{
                                token: jData.token
                            }
                        }).then(res=>{
                            this.showLoginWin = false;
                            this.$message(res.data.msg);
                            // console.log(res.data.data.user.headimg)
                            this.myinfo = res.data.data;
                            this.$emit("logined", this.myinfo);
                            // if (res.data.data.goto) {
                            //     location.href = res.data.data.goto
                            // }
                        })
                    } else {
                        this.updateTip(jData.user.name + "已扫码", 'scan-message');
                        this.$refs.tipFresh.textContent = "";
                        this.$refs.ImageCode.style.pointerEvents = 'none';
                    }
                };
            } else {
                alert("未能识别二维码。");
            }
        }
    }
});
